// 主题管理模块
export function initTheme() {
    const toggleButton = document.getElementById('theme-toggle');
    const savedTheme = localStorage.getItem('theme');
    const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;

    if (savedTheme === 'dark' || (!savedTheme && systemPrefersDark)) {
        document.documentElement.setAttribute('data-theme', 'dark');
        toggleButton.textContent = '☀️ 亮色模式';
    } else {
        document.documentElement.setAttribute('data-theme', 'light');
        toggleButton.textContent = '🌙 暗色模式';
    }
    
    // 绑定事件
    toggleButton.addEventListener('click', () => toggleTheme(toggleButton));
}

export async function toggleTheme(btnElement) {
    const currentTheme = document.documentElement.getAttribute('data-theme');
    const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
    
    // 立即更新界面
    document.documentElement.setAttribute('data-theme', newTheme);
    btnElement.textContent = newTheme === 'dark' ? '☀️ 亮色模式' : '🌙 暗色模式';
    
    console.log('🎯 开始保存主题偏好...');
    
    try {
        console.log('⏳ 等待异步保存完成...');
        const result = await slowSaveTheme(newTheme);
        console.log(result);
        console.log('🎉 保存成功，所有操作完成！');
    } catch (error) {
        console.error(error);
        console.log('⚠️ 主题已切换，但偏好保存失败，下次可能恢复默认设置');
    }
    
    console.log('================================');
}

// 异步保存函数
function slowSaveTheme(newTheme) {
    return new Promise((resolve, reject) => {
        console.log('🚀 异步保存任务已启动...');
        setTimeout(() => {
            if (Math.random() > 0.5) {
                reject('💥 保存失败：网络连接异常！');
            } else {
                localStorage.setItem('theme', newTheme);
                resolve('✅ 主题偏好已保存到本地存储！');
            }
        }, 1000); // 缩短到1秒，便于测试
    });
}

// 系统主题变化监听
export function setupThemeListener() {
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
        if (!localStorage.getItem('theme')) {
            if (e.matches) {
                document.documentElement.setAttribute('data-theme', 'dark');
            } else {
                document.documentElement.setAttribute('data-theme', 'light');
            }
        }
    });
}